﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;

/// <summary>
/// 
/// </summary>
public partial class UserDefinedFunctions
{
	/// <summary>
	/// 
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[Microsoft.SqlServer.Server.SqlFunction]
	public static SqlString DoubleByteToHtmlEncoding(SqlString input)
	{
		// check for null
		if (input.IsNull == true) return input;

		// convert the sql string to a .net string
		char[] chars = input.ToString().ToCharArray();

		// create a string builder to hold the converted output, slightly larger than
		// the source string
		StringBuilder Result = new StringBuilder(chars.Length + (int)(chars.Length * 0.1));

		foreach (char c in chars)
		{
			int Value = Convert.ToInt32(c);

			// if the value is larger than an ascii value, escape it
			if (Value > 127)
				Result.AppendFormat("&#{0};", Value);
			// otherwise add it as is
			else
				Result.Append(c);
		}

		// return the processed result to sql
		return new SqlString(Result.ToString());
	}
};

